var app=angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
		when('/', {templateUrl: 'stbtocust.html', controller: paycont}).
		when('/cancel/', {templateUrl: 'stbtocust.html', controller: paycont}). 
		otherwise({redirectTo: '/'});
}]);


function paycont($scope, $http,$window,$location,$filter)
 {
    $scope.count = 0;   
	$scope.currentPage = 0;
    $scope.pageSize = 25;
	$scope.Math = window.Math;	
	var d = new Date();		
	$scope.stbc={};		
	$scope.custarr = [];
	$scope.custidarr = [];	 
	$scope.stbarr = [];	 
	$scope.cardarr = [];	 
	
	$http.get('stbcustdata.php?q=2').success(function(data) {
		for(var i=0;i<data.length;i++)
			$scope.stbarr[i] = data[i].stbno;		
			$scope.cardarr[i] = data[i].cardno;		
    });
	/*$http.get('stbcustdata.php?q=2.2').success(function(data) {
		for(var i=0;i<data.length;i++)
			$scope.fullstbarr[i] = data[i];		
    });*/
	$http.get('stbcustdata.php?q=3').success(function(data) {
		for(var i=0;i<data.length;i++){
			$scope.custarr[i] = data[i].cname;								
		}			
    });	
	
	$http.get('stbcustdata.php?q=1').success(function(data) {
		$scope.stbcust = data;
    });			
	
	$scope.stbgiven= function()
	{
		if($scope.stbc.stbno){		
			var url = 'stbcustdata.php?q=4&stbno='+$scope.stbc.stbno;
			$http.get(url).success(function(data) {
			//location.href=url;
				$scope.stbc.cardno = data;
			});		
		}
	}
	
	$scope.cardgiven= function()
	{
		if($scope.stbc.cardno){		
			var url = 'stbcustdata.php?q=5&cardno='+$scope.stbc.cardno;		
			$http.get(url).success(function(data) {
				$scope.stbc.stbno = data;
			});		
		}
	}
	
	$scope.edit= function(id)
	{
		for(i in $scope.stbcust) {
			if($scope.stbcust[i].id == id)
			{          
              $scope.stbc = angular.copy($scope.stbcust[i]);							  
			}
        }		
		$scope.ed = true;	
	}
	
	$scope.save= function()
	{
		if(!$scope.stbc.stbno || !$scope.stbc.custname || !$scope.stbc.actdt || !$scope.stbc.rpm)
			alert("Please enter all the fields marked with *");
		else{		
			var valid1=false;				
			for(var i=0;i<$scope.stbarr.length;i++)			
				if($scope.stbarr[i] == $scope.stbc.stbno)
					valid1=true;
			
			var valid2=false;			
			for(var i=0;i<$scope.custarr.length;i++)			
				if($scope.custarr[i] == $scope.stbc.custname)
					valid2=true;
					
			var valid3=true;			
			for(var i in $scope.stbcust)						
				if($scope.stbcust[i].cardno == $scope.stbc.cardno || $scope.stbcust[i].stbno == $scope.stbc.stbno)
					valid3=false;					
			
			if(!valid1 || !valid2 || !valid3)
			{
				if(!valid1)
					alert("Entered STB does not exist/is not ready to be assigned...");
				if(!valid2)
					alert("Entered Customer does not exist...");
				if(!valid3)
					alert("Entered stb or card number is already assigned");
			}				
			
			else{					
				var sql = 'stbtocust_cud.php?q=c&dataset='+JSON.stringify($scope.stbc);			
				$http.get(sql).success(function(data) {		
				    //location.href=sql;
					alert("Record saved");
					$scope.cancel();
				});	
			}
		}			
	}
	
	$scope.upd= function(id)
	{
		if(!$scope.stbc.stbno || !$scope.stbc.custname || !$scope.stbc.actdt || !$scope.stbc.rpm)
			alert("Please enter all the fields marked with *");
		else{
			/*var valid1=false;	
			for(var i=0;i<$scope.stbarr.length;i++)			
				if($scope.stbarr[i] == $scope.stbc.stbno)
					valid1=true;*/
			
			var valid2=false;			
			for(var i=0;i<$scope.custarr.length;i++)			
				if($scope.custarr[i] == $scope.stbc.custname)
					valid2=true;							
			
			//if(!valid1 || !valid2)
			if(!valid2)
			{
				//if(!valid1)
					//alert("Entered STB does not exist/is not ready to be assigned...");
				if(!valid2)
					alert("Entered Customer does not exist...");
			}
			else{					
				var sql = 'stbtocust_cud.php?q=u&dataset='+JSON.stringify($scope.stbc);			
				$http.get(sql).success(function(data) {				
					alert("Record "+$scope.stbc.id+" updated");
					//location.href=sql;
					$scope.cancel();
				});	
			}
		}		
	}
	
	$scope.dlt= function(id)
	{		
		var sql = 'stbtocust_cud.php?q=d&id='+id;		
		$http.get(sql).success(function(data) {				
			alert("Record "+id+" deleted");
		});
		$scope.cancel();
	}
	
	$scope.cancel= function()
	{		 	
		$scope.activePath = null;
		$scope.activePath = $location.path('stbtocust.php');	
	};
 }
 
 app.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'yy-mm-dd',
                onSelect: function (date) {
                    scope.$apply(function () {
                        ngModelCtrl.$setViewValue(date);
                    });											
                }				
            });			
        }
    };
});
app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

app.directive('myBlur', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('blur', function () {
                //apply scope (attributes)
                scope.$apply(attr.myBlur);
                //return scope value for focusing to false
                scope.$eval(attr.myFocus + '=false');
            });
        }
    };
});
app.directive('capitalize', function() {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
           if(inputValue == undefined) inputValue = '';
           var capitalized = inputValue.toUpperCase();
           if(capitalized !== inputValue) {
              modelCtrl.$setViewValue(capitalized);
              modelCtrl.$render();
            }         
            return capitalized;
         }
         modelCtrl.$parsers.push(capitalize);
         capitalize(scope[attrs.ngModel]);  // capitalize initial value
     }
   };
});

app.filter('exact', function(){
  return function(items, match){
    var matching = [], matches, falsely = true;
	angular.forEach(match, function(value, key){
      falsely = falsely && !value;
    });
    if(falsely){
      return items;
    }
    angular.forEach(items, function(item){ // e.g. { title: "ball" }
      matches = true;
      angular.forEach(match, function(value, key){ // e.g. 'all', 'title'
        if(!!value) // do not compare if value is empty
          matches = matches && (item[key] === value);          
      });
      if(matches)
        matching.push(item);        
    });
    return matching;
  }
});

app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    };
});